package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.kuaidi100.sdk.api.AutoNum;
import com.kuaidi100.sdk.response.AutoNumResp;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.kuaidi100.sdk.utils.PropertiesReader;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.common.utils.OrderUtils;
import com.ytjj.qmyx.mall.config.SupplyApiConfig;
import com.ytjj.qmyx.mall.enums.OrderStatusEnums;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.dto.OrderInfoReturnDTO;
import com.ytjj.qmyx.mall.model.request.OrderQueryRequest;
import com.ytjj.qmyx.mall.model.request.ReturnAddExpressRequest;
import com.ytjj.qmyx.mall.model.request.ReturnCommitRequest;
import com.ytjj.qmyx.mall.model.request.UpdateOrderStatusRequest;
import com.ytjj.qmyx.mall.model.response.OrderQueryResponse;
import com.ytjj.qmyx.mall.model.response.ReturnGoodsResponse;
import com.ytjj.qmyx.mall.model.vo.ReturnGoodsVO;
import com.ytjj.qmyx.mall.service.ReturnService;
import com.ytjj.qmyx.mall.utils.MallStringUtil;
import com.ytjj.qmyx.users.client.AdminClient;
import com.ytjj.qmyx.users.mapper.UsersMapper;
import com.ytjj.qmyx.users.model.Users;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 *
 *  *
 **/
@Service
@Slf4j
public class ReturnServiceImpl implements ReturnService {

    @Resource
    private OrderInfoDao orderInfoDao;

    @Resource
    private OrdersDao ordersDao;

    @Resource
    private ReturnGoodsDao returnGoodsDao;

    @Resource
    private ReturnGoodsMapper returnGoodsMapper;

    @Resource
    private ProductMapper productMapper;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private SupplyApiConfig supplyApiConfig;

    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisService redisService;

    @Resource
    private ExpressCompanyMapper expressCompanyMapper;
    @Resource
    private ReturnRegisterMapper returnRegisterMapper;
    @Resource
    private AdminClient adminClient;
    @Resource
    private OrdersPayMapper ordersPayMapper;
    @Resource
    private OrderDisparitiesRefundListMapper orderDisparitiesRefundListMapper;
    @Resource
    private UsersMapper usersMapper;

    @Override
    public ReturnGoodsResponse create(Integer userId, Integer orderInfoId) {
        ReturnGoods byOrderInfoId = returnGoodsDao.findByOrderInfoId(orderInfoId);

        if(null != byOrderInfoId) {
            //存在直接返回
            if(userId == null || ! userId.equals(byOrderInfoId.getUserId())) {
                throw new ApiException("操作权限错误，请联系客服！");
            }
            return getReturnGoods(byOrderInfoId);
        }

        OrderInfoReturnDTO orderInfoReturnDTO = orderInfoDao.findById(orderInfoId);
        if(null == orderInfoReturnDTO) {
            throw new ApiException("未找到订单,或当前订单未支付！");
        }
        if(userId == null || ! userId.equals(orderInfoReturnDTO.getUserId())) {
            throw new ApiException("操作权限错误，请联系客服！");
        }

        Integer addressId = returnGoodsDao.selectAddressId(orderInfoReturnDTO.getProductId());

        ReturnGoods returnGoods = new ReturnGoods();
        returnGoods.setServiceNo(OrderUtils.getRefundCode(userId));
        returnGoods.setOrdersInfoId(orderInfoId);
        returnGoods.setAmount(orderInfoReturnDTO.getProductPrice());
        returnGoods.setProductId(orderInfoReturnDTO.getProductId());
        returnGoods.setSpec(orderInfoReturnDTO.getProductSkuSpec());
        returnGoods.setNumber(orderInfoReturnDTO.getProductSum());
        returnGoods.setUserId(userId);
        returnGoods.setStatus(0);
        returnGoods.setAddressId(addressId);
        returnGoodsMapper.insertSelective(returnGoods);
        return getReturnGoods(returnGoods);
    }

    public ReturnGoodsResponse getReturnGoods(ReturnGoods returnGoods) {
        Product product = productMapper.selectByPrimaryKey(returnGoods.getProductId());
        ReturnGoodsResponse response = new ReturnGoodsResponse();
        BeanUtils.copyProperties(returnGoods, response);
        if (null != returnGoods.getServiceApplyTime()){
            response.setSendBackExpirationTime(getDate(returnGoods.getServiceApplyTime(), 24 * 3));
        }
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(returnGoods.getOrdersInfoId());
        response.setProductOprice(ordersInfo.getProductOprice());////商品原价--优惠之前
        response.setReducedPrice(ordersInfo.getProductOprice().subtract(ordersInfo.getProductPrice()));//优惠金额
        response.setProductPrice(ordersInfo.getProductPrice());//优惠后的金额
        response.setProductName(product.getProductName());
        response.setProductImg(product.getProductImg());
        response.fallTime();
        if( returnGoods.getAfterType() == 2 && (response.getStatus().equals(8) || response.getStatus().equals(9) || response.getStatus().equals(4) || response.getStatus().equals(3) ||  response.getStatus().equals(5))) {
            response.setQueryTrackResp(getExpress(returnGoods.getServiceNo()));
        }
        //根据地址id查一下退货地址信息
        //退货地址
        if (null != returnGoods.getAddressId()){
            Map<String,String> map = new HashMap<>();
            map.put("addressId",String.valueOf(returnGoods.getAddressId()));
            String s = HttpClientUtil.doGet(supplyApiConfig.getUrl() +"/product/getAddress", map, supplyApiConfig.getHeadsMap());
            YxBankerStoreAddress yxBankerStoreAddress = JSONObject.parseObject(s, YxBankerStoreAddress.class);
            response.setReceivingPerson(yxBankerStoreAddress.getName());
            response.setReceivingPhone(yxBankerStoreAddress.getTel());
            response.setReceivingAddress(yxBankerStoreAddress.getPCAaddress());
        }

        if (null == returnGoods.getAfterType() && response.getAfterType() != 2){
            response.setFailRemarks(response.getServiceRemarks());
        }else {
            if (!StringUtils.isEmpty(response.getServiceRemarks())){
                response.setFailRemarks(response.getServiceRemarks());
            }
            if (!StringUtils.isEmpty(response.getBankerRemarks())){
                response.setFailRemarks(response.getBankerRemarks());
            }
        }
        if (null != returnGoods.getAfterType() && response.getAfterType() == 1){
            if (!StringUtils.isEmpty(response.getBankerRemarks())){
                response.setFailRemarks(response.getBankerRemarks());
            }
            if (!StringUtils.isEmpty(response.getServiceRemarks())){
                response.setFailRemarks(response.getServiceRemarks());
            }
        }

//        申请退货的次数
        String applyNum = redisService.get("return:good:num" + returnGoods.getOrdersInfoId());
        response.setReturnGoodNum(Integer.valueOf(StringUtils.isEmpty(applyNum) ? "0" : applyNum));
        //客服审核不通过的次数
        String failNum = redisService.get("return:good:audit:fail:" + returnGoods.getOrdersInfoId());
        response.setFailNum(Integer.valueOf(StringUtils.isEmpty(failNum) ? "0" : failNum));
        //用户撤回次数
        String revokeNum = redisService.get("return:good:revoke:" + returnGoods.getOrdersInfoId());
        response.setRevokeNum(Integer.valueOf(StringUtils.isEmpty(revokeNum) ? "0" : revokeNum));

        OrdersInfoFreightDto ordersInfoFreightDto = ordersDao.selectFreightByChildOrderNo(ordersInfo.getChildOrderNo());
        BigDecimal freight = BigDecimal.ZERO;
        if (null != ordersInfoFreightDto){
            freight = ordersInfoFreightDto.getFreight();
        }
        response.setProductPriceAndFreights(ordersInfo.getProductPrice().multiply(BigDecimal.valueOf(ordersInfo.getProductSum())).add(freight));
        BigDecimal add = ordersInfo.getProductPrice().add(freight);
        if (null != add){
            response.setProductPrice(add);
        }
        //退货流程优化  修改状态
        if (ordersInfo.getIsRefund().intValue() ==1){
            response.setStatus(9);
        }else {
            //查询是否同步到原路返回页
            ReturnRegisterExample example = new ReturnRegisterExample();
            example.createCriteria().andOrderInfoIdEqualTo(ordersInfo.getId()).andStatusEqualTo(0);
            long count = returnRegisterMapper.countByExample(example);
            if (count>0 &&  (returnGoods.getStatus().equals(3) || returnGoods.getStatus().equals(4) || returnGoods.getStatus().equals(8))){
                response.setStatus(4);
            }
        }
        return response;
    }

    @Override
    public void commitReturn(ReturnCommitRequest request) {
        ReturnGoods returnGoods = returnGoodsDao.findByServiceNo(request.getServiceNo());
        if(returnGoods == null) {
            throw new ApiException("找不到当前退货单！");
        }
        if(request.getUserId() == null || ! request.getUserId().equals(returnGoods.getUserId())) {//|| (!returnGoods.getStatus().equals(0)) && !returnGoods.getStatus().equals(5)
            throw new ApiException("操作权限错误，请联系客服！");
        }
        if (!returnGoods.getStatus().equals(0) && !returnGoods.getStatus().equals(5) && !returnGoods.getStatus().equals(6) && !returnGoods.getStatus().equals(7)) {
            throw new ApiException("退货申请不能重复发起！");
        }
        returnGoods.setIsGet(request.getIsGet());
        returnGoods.setReturnReason(request.getReturnReason());
        returnGoods.setUserRemarks(request.getUserRemarks());
        returnGoods.setUserRemarksImg(request.getUserRemarksImg());
        returnGoods.setCreateTime(new Date());
        returnGoods.setStatus(1);
        returnGoods.setUpdateTime(null);
        returnGoodsMapper.updateByPrimaryKeySelective(returnGoods);

    }

    @Override
    public ReturnGoodsResponse appCreate(Integer userId, Integer orderInfoId) {
        OrderInfoReturnDTO orderInfoReturnDTO = orderInfoDao.findById(orderInfoId);
        ReturnGoodsResponse response = new ReturnGoodsResponse();
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(orderInfoId);
        OrdersInfoFreightDto dto = ordersDao.selectFreightByChildOrderNo(ordersInfo.getChildOrderNo());
        Product product = productMapper.selectByPrimaryKey(ordersInfo.getProductId());
        response.setProductOprice(ordersInfo.getProductOprice());////商品原价--优惠之前
        response.setReducedPrice(ordersInfo.getProductOprice().subtract(ordersInfo.getProductPrice()));//优惠金额
        response.setProductPrice(ordersInfo.getProductPrice());//优惠后的金额
        response.setProductName(product.getProductName());
        response.setProductImg(product.getProductImg());
        response.setNumber(ordersInfo.getProductSum());
        response.setAmount(orderInfoReturnDTO.getProductPrice().multiply(BigDecimal.valueOf(orderInfoReturnDTO.getProductSum())));
        response.setSpec(orderInfoReturnDTO.getProductSkuSpec());
        response.setProductId(orderInfoReturnDTO.getProductId());
        response.setFreight(null != dto ? dto.getFreight() : BigDecimal.valueOf(0));
        BigDecimal add = ordersInfo.getProductPrice().multiply(BigDecimal.valueOf(ordersInfo.getProductSum())).add(response.getFreight());
        if (null != add){
            response.setProductPriceAndFreights(add);
            response.setProductPrice(add);
            response.setAmount(add);
        }
        return response;
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public CommonResult appComminReturn(ReturnCommitRequest request) {
        OrdersInfo info = ordersInfoMapper.queryByChildOrderNo(request.getChildOrderNo());
        if (info !=null) {
            request.setOrderInfoId(info.getId());
        }
        RLock lock = redissonClient.getLock("RETURN_GOODS_LOCK_" + request.getOrderInfoId());
        boolean b = false;
        try {
            b = lock.tryLock(0, 5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            lock.unlock();
        }
        if (!b) {
            throw new ApiException("售后申请中,请勿重复申请");
        }
        // 已收到状态下图片不能为空
        if (1 == request.getIsGet()) {
            if (StringUtils.isEmpty(request.getUserRemarksImg())) {
                throw new ApiException("请上传包装图和实物图，我们会尽快审核哦~");
            }
        }
        //查询该订单是否被受理售后
        String rejectType = redisService.get("return:good:audit:reject:type:" + request.getOrderInfoId());
        if (!StringUtils.isEmpty(rejectType) && rejectType.equals("2")){
            throw new ApiException("该退货不受理，不能重复发起，有疑问请联系客服处理");
        }
        //订单签收超7天不能退货
        OrderInfoReturnDTO orderInfoReturnDTO = orderInfoDao.findById(request.getOrderInfoId());
        if (null != orderInfoReturnDTO && null != orderInfoReturnDTO.getReceiveTime()) {
            Date receiveTime = orderInfoReturnDTO.getReceiveTime();//收货时间
            Date newTime = new Date();//现在
            int days = (int) ((newTime.getTime() - receiveTime.getTime()) / (1000 * 3600 * 24));
            if (days > 30) {
                throw new ApiException("该订单签收已超30天,不能发起退货,有疑问请联系客服,谢谢");
            }
        }

        //查询子订单信息
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(request.getOrderInfoId());

//        List<ReturnGoods> returnGoodsList = returnGoodsDao.findReturnGoodsByOrderInfoId(request.getOrderInfoId());
//
//        if (!CollectionUtils.isEmpty(returnGoodsList)) {
//            returnGoodsList.stream().forEach(returnGoods ->{
//                if (returnGoods.getStatus().equals(1) && ordersInfo.getOrderinfoStatus().equals("6")) {
//                    throw new ApiException("售后申请正在审核中，不能重复发起！");
//                }
//                if ( returnGoods.getStatus().equals(4)){
//                    throw new ApiException("售后处理已完成，不能重复发起！");
//                }
//                if ( returnGoods.getStatus() != 5 && returnGoods.getStatus() != 6 && returnGoods.getStatus() != 7) {
//                    throw new ApiException("售后正在处理中，不能重复发起！");
//                }
//            });
//        }
        //查询是否存在退货管理中
        ReturnGoods returnGoods1 = returnGoodsDao.selectByOrderInfoId(request.getOrderInfoId());
        if(null != returnGoods1) {
            if(9 != returnGoods1.getStatus()){
                throw new ApiException("该订单已经在售后中");
            }else {
                throw new ApiException("该订单售后已完成");
            }
        }

        try {
            if (checkAbroadOrderCancel(ordersInfo.getChildOrderNo(), ordersInfo.getBankerId(), orderInfoReturnDTO.getUserId()) != 1) {
                throw new ApiException("商品已出库，不能申请退款，有疑问请联系客服！");
            }
        } catch (Exception e) {
            log.error("===跨境订单检查能否退货异常==={}", e);
        }

        Orders orders = ordersMapper.selectById(ordersInfo.getOrderId());
        List<OrderDisparitiesRefundResponse> orderDisparitiesRefunds = orderDisparitiesRefundListMapper.querySuccessByOrderNo(orders.getOrderNo());
        BigDecimal refundMoney= BigDecimal.ZERO;
        if (!CollectionUtils.isEmpty(orderDisparitiesRefunds)) {
            refundMoney = orderDisparitiesRefunds.stream().map(item -> ObjectUtils.isEmpty(item.getAmount()) ? new BigDecimal(0) : item.getAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
        }

        OrdersPay ordersPay = ordersPayMapper.findOrdersPayByOrderNo(orders.getOrderNo());
        BigDecimal amount = ordersPay.getAmount().subtract(refundMoney);
        try {
            if(null != ordersPay && amount.compareTo(request.getAmount())<0){
                throw new ApiException("提交售后金额不能大于实付金额！");
            }
        }catch (Exception e) {
            log.error("检查售后订单金额异常");
            throw new ApiException("提交售后金额不能大于实付金额！");
        }


        List<String> childOrderNo = new ArrayList<>();
        childOrderNo.add(ordersInfo.getChildOrderNo());
        List<OrderQueryResponse> orderQueryResponses = querySupplyChainOrderInfo(childOrderNo);
        if (!CollectionUtils.isEmpty(orderQueryResponses)) {
            OrderQueryResponse orderQueryResponse = orderQueryResponses.get(0);
            if (request.getAfterType() == 1) {
                if (null != orderQueryResponse.getOrderInfoStatus() && !orderQueryResponse.getOrderInfoStatus().equals(1)) {
                    throw new ApiException("商品正在打包中，不能申请退款，有疑问请联系客服处理");
                }
            }
        }

        Product product = productMapper.selectByPrimaryKey(orderInfoReturnDTO.getProductId());

        String addressId = "";

        try {
            if (null!= product){
                Map<String,String> map = new HashMap<>();
                map.put("productId",String.valueOf(product.getSupplyProductId()));
                addressId = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/getAddressId", map, supplyApiConfig.getHeadsMap());
                log.info("=========获取售后地址===========addressId{}",addressId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ReturnGoods returnGoods = new ReturnGoods();
        returnGoods.setServiceNo(OrderUtils.getRefundCode(request.getUserId()));
        returnGoods.setOrdersInfoId(request.getOrderInfoId());
        returnGoods.setAmount(request.getAmount());
        if (1 == request.getAfterType()){
            BigDecimal freight = ordersInfoMapper.selectByChildOrderNo(ordersInfo.getChildOrderNo());
            if (null == freight){
                freight = BigDecimal.valueOf(0);
            }
            returnGoods.setAmount(orderInfoReturnDTO.getProductPrice().multiply(BigDecimal.valueOf(orderInfoReturnDTO.getProductSum())).add(freight));
        }
        returnGoods.setProductId(orderInfoReturnDTO.getProductId());
        returnGoods.setSpec(orderInfoReturnDTO.getProductSkuSpec());
        returnGoods.setNumber(orderInfoReturnDTO.getProductSum());
        returnGoods.setUserId(orderInfoReturnDTO.getUserId());
        returnGoods.setAddressId(org.apache.commons.lang3.StringUtils.isNotBlank(addressId) ? Integer.valueOf(addressId) : null);
        returnGoods.setIsGet(request.getIsGet());
        returnGoods.setReturnReason(request.getReturnReason());
        returnGoods.setUserRemarks(request.getUserRemarks());
        if ( ordersInfo.getOrderinfoStatus().equals("1") || org.apache.commons.lang3.StringUtils.isBlank(ordersInfo.getExpressNo())) {
            request.setAfterType(1);
        }
//        if (request.getAfterType() == 1){
//            returnGoods.setUserRemarks(null);
//        }
        returnGoods.setUserRemarksImg(request.getUserRemarksImg());
        returnGoods.setCreateTime(new Date());
        returnGoods.setStatus(1);
        returnGoods.setUpdateTime(null);
        returnGoods.setServiceStatus(1);
        returnGoods.setServiceRemarks(null);
        returnGoods.setBankerStatus(1);
        returnGoods.setBankerRemarks(null);
        returnGoods.setAfterType(request.getAfterType());
        returnGoods.setServiceCheckIn(0);
        returnGoods.setBankerId(ordersInfo.getBankerId());
        returnGoods.setShopId(supplyApiConfig.getShopId());
        returnGoods.setChildOrderNo(ordersInfo.getChildOrderNo());
        returnGoods.setProductNum(ordersInfo.getProductSum());
        returnGoods.setIsLink(request.getIsLink());
        //记录客服操作人员
        KfAdmin kfAdmin = returnGoodsDao.findKfAdminId(request.getKfid());
        if (kfAdmin!=null){
            returnGoods.setServiceId(kfAdmin.getId());
            returnGoods.setServiceName(kfAdmin.getName());
//            returnGoods.setAfterSalesPassUser(kfAdmin.getId());
//            returnGoods.setAfterSalesPassTime(new Date());
        }

        //记录申请退货的次数
        redisService.increment("return:good:num" + request.getOrderInfoId(),1);
        //订单状态是售后状态
        String orderInfoStatus = ordersInfo.getOrderinfoStatus();
        if (StringUtils.isEmpty(orderInfoStatus) || OrderStatusEnums.REFUND.getValue().equals(orderInfoStatus)) {
            if (!StringUtils.isEmpty(info.getExpressNo()) && !StringUtils.isEmpty(info.getExpressCompanyNo())) {
                orderInfoStatus = OrderStatusEnums.SHIPPED.getValue();
            } else {
                orderInfoStatus = OrderStatusEnums.UNSHIPPED.getValue();
            }
        } else {
            orderInfoStatus = info.getOrderinfoStatus();
        }
        //redis保存原状态
        adminClient.updateRedisString("return:good:orderInfoStatus" + request.getOrderInfoId(),orderInfoStatus,3600 * 24 * 180);
        /**
         * 保存原状态
         */
        returnGoods.setOrdersStatus(orderInfoStatus);

        Integer count = updateOrderStatus(ordersInfo);//修改订单状态为售后订单
        if (count < 1){
            throw new ApiException("系统异常,请稍后再试");
        }
        //验证订单是否存在供应链
        if (1 == request.getAfterType()) {

            OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
            orderQueryRequest.setChildOrderNo(childOrderNo);
            String jsonStr = JSONObject.toJSONString(orderQueryRequest);
            String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/selectByChildOrderNo", jsonStr, supplyApiConfig.getHeadsMap());
            log.info("=========销售端存在供应链不存在的订单===========childOrderNo:{}",resultJson);
            if (!StringUtils.isEmpty(resultJson)) {
                List<String> childOrderNoList = JSONArray.parseArray(resultJson, String.class);
                if (!CollectionUtils.isEmpty(childOrderNoList)){
                    returnGoods.setBankerStatus(2);
                    returnGoods.setBankerApplyTime(new Date());
                    returnGoods.setStatus(4);
                    //客服审核直接通过然后同步到原路返回页
                    returnGoods.setServiceStatus(2);
                    returnGoods.setServiceApplyTime(new Date());
                    String json = JSON.toJSONString(returnGoods);
                    log.info("======用户申请售后======{}",json);
                    returnGoodsMapper.insertSelective(returnGoods);
                    //退款类型的售后单自动登记售后责任表
                    try {
                        adminClient.saveReturnDuty(returnGoods.getServiceNo());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try{
                        //支付宝支付的订单，客服手动同步到原路返回页
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(orders.getPaySource()) && "alipay".equals(orders.getPaySource().toLowerCase())) {
                            adminClient.syncReturnRegisterById(returnGoods.getId());
                        }
                    }catch (Exception e) {
                        log.error("退款售后单同步到原路返回页失败:{}",e);
                    }

                    if (null != lock) {
                        lock.unlock();
                    }
                    return CommonResult.success(returnGoods);
                }
            }

        }
        returnGoodsMapper.insertSelective(returnGoods);
        //退款类型的售后单自动登记售后责任表
        try {
            if (1 == request.getAfterType()) {
                adminClient.saveReturnDuty(returnGoods.getServiceNo());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            //上传供应链
            String json = JSON.toJSONString(returnGoods);
            log.info("======售后上传供应链======{}",json);
            String s = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/returnGoodsUpload", json, supplyApiConfig.getHeadsMap());
            log.info("====售后上传供应链===结束==={}",s);
        } catch (Exception e) {
            log.error("======售后上传供应链失败======{}",e);
        }
        if (null != lock) {
            lock.unlock();
        }
        return CommonResult.success(returnGoods);
    }

    /**
     * 检查跨境订单是否能退款
     * @param childOrderNo
     * @param bankerId
     * @param userId
     * @return 1=能 0=不能
     */
    private Integer checkAbroadOrderCancel(String childOrderNo, Integer bankerId, Integer userId) {
        YxReturnGoods yxReturnGoods = new YxReturnGoods();
        yxReturnGoods.setChildOrderNo(childOrderNo);
        yxReturnGoods.setBankerId(bankerId);
        yxReturnGoods.setUserId(userId);
        String json = com.gexin.fastjson.JSON.toJSONString(yxReturnGoods);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/checkAbroadOrderCancel", json, supplyApiConfig.getHeadsMap());
        log.info("===checkAbroadOrderCancel==={},{}", childOrderNo, resultJson);
        if (org.springframework.util.StringUtils.isEmpty(resultJson)) {
            log.warn("===供应链检查跨境订单是否能发货返回空了===");
            return 0;
        }
        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        if (null != result && result.getCode()==200) {
            return 1;
        }
        return 0;
    }

    /**
     * 修改订单状态为售后订单
     * @param ordersInfo
     */
    private Integer updateOrderStatus(OrdersInfo ordersInfo) {
        //修改订单状态
        ordersInfo.setOrderinfoStatus("6");
        Integer i = ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
        if (i > 0){
            try {
                UpdateOrderStatusRequest updateOrderStatusRequest = new UpdateOrderStatusRequest();
                updateOrderStatusRequest.setChildOrderNo(ordersInfo.getChildOrderNo());
                updateOrderStatusRequest.setShopId(supplyApiConfig.getShopId());
                updateOrderStatusRequest.setOrderStatus(6);
                String json = JSON.toJSONString(updateOrderStatusRequest);
                String s = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/updateOrderStatus", json, supplyApiConfig.getHeadsMap());
                log.info("=====修改订单状态======{}",s);
            } catch (Exception e) {
                e.printStackTrace();
            }
            OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
            ordersInfoExample.createCriteria().andOrderIdEqualTo(ordersInfo.getOrderId());
            List<OrdersInfo> ordersInfos = ordersInfoMapper.selectByExample(ordersInfoExample);
            if (ordersInfos.size() == 1){
                //修改主订单状态
                ordersMapper.updateOrderStatus(ordersInfo.getOrderId(),6);
            }else {
                //判断其他子订单是否为6.售后订单,是就把主订单状态也修改为6.售后订单
                AtomicReference<Boolean> flag = new AtomicReference<>(true);
                ordersInfos.stream().filter(item ->item.getId() != ordersInfo.getId()).forEach(item ->{
                    if (!item.getOrderinfoStatus().equals("6")) {
                        flag.set(false);
                    }
                });
                if (flag.get()){
                    ordersMapper.updateOrderStatus(ordersInfo.getOrderId(),6);
                }
            }
        }
        return i;
    }

    @Override
    public List<ReturnGoodsVO> selectReturnGoods(Integer pageNum,Integer pageSize,Integer type, String token) {
        Users users = usersMapper.queryUsersByToken(token);
        if (ObjectUtils.isEmpty(users)) {
            return null;
        }
        PageHelper.startPage(pageNum,pageSize);
        List<ReturnGoodsVO> returnGoodsVOList = returnGoodsDao.selectReturnGoods(type, users.getId());
        returnGoodsVOList.stream().forEach(item ->{
            if (item.getAfterType() != 1 ){
                if (org.apache.commons.lang3.StringUtils.isNotBlank(item.getServiceRemarks())){
                    item.setFailRemarks(item.getServiceRemarks());
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(item.getBankerRemarks())){
                    item.setFailRemarks(item.getBankerRemarks());
                }
            }else {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(item.getBankerRemarks())){
                    item.setFailRemarks(item.getBankerRemarks());
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(item.getServiceRemarks())){
                    item.setFailRemarks(item.getServiceRemarks());
                }
            }


            if (null != item.getServiceApplyTime()){
                item.setSendBackExpirationTime(getDate(item.getServiceApplyTime(), 24 * 3));
            }
            //用户撤回次数
            String revokeNum = redisService.get("return:good:revoke:" + item.getServiceNo());
            item.setRevokeNum(Integer.valueOf(org.springframework.util.StringUtils.isEmpty(revokeNum) ? "0" : revokeNum));

            if (item.getIsRefund()!=null && item.getIsRefund()==1){
                item.setStatus(9);
            }else {
                //查询是否同步到原路返回页
                ReturnRegisterExample example = new ReturnRegisterExample();
                example.createCriteria().andOrderInfoIdEqualTo(item.getOrdersInfoId()).andStatusEqualTo(0);
                long count = returnRegisterMapper.countByExample(example);
                if (count>0 && (item.getStatus().equals(3) || item.getStatus().equals(4) || item.getStatus().equals(8))){
                    item.setStatus(4);
                }
            }
        });
        return returnGoodsVOList;
    }

    /**
     *  计算初始时间加一小时
     * @param date 初始时间
     * @return
     */
    public static Date getDate(Date date,Integer hour) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 24小时制
        cal.add(Calendar.HOUR, hour);
        return cal.getTime();
    }
    /**
     * 获取退货进度
     * @param returnGoodsId 退货表id
     * @return
     */
    @Override
    public CommonResult getReturnGoodsProgress(Integer returnGoodsId) {
        ReturnGoods returnGoods = returnGoodsMapper.selectByPrimaryKey(returnGoodsId);
        if (null == returnGoods){
            throw new ApiException("查询退货信息异常");
        }

        ReturnRegisterExample returnRegisterExample = new ReturnRegisterExample();
        returnRegisterExample.createCriteria().andOrderInfoIdEqualTo(returnGoods.getOrdersInfoId()).andStatusEqualTo(0);
        ReturnRegister returnRegister = new ReturnRegister();
        List<ReturnRegister> returnRegisters = returnRegisterMapper.selectByExample(returnRegisterExample);
        if (!CollectionUtils.isEmpty(returnRegisters)){
            returnRegister = returnRegisters.get(0);
        }

        Integer afterType = returnGoods.getAfterType();
        Integer serviceStatus = returnGoods.getServiceStatus();
        Integer bankerStatus = returnGoods.getBankerStatus();
        Integer status = returnGoods.getStatus();
        //退货流程优化
        if (returnRegister.getId()!=null){
            OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(returnGoods.getOrdersInfoId());
            if (ordersInfo!=null && ordersInfo.getIsRefund()==1){
                status=9;
            }else {
                if (returnGoods.getStatus().equals(3) || returnGoods.getStatus().equals(4) || returnGoods.getStatus().equals(8)){
                    status=4;
                }
            }
        }

        Boolean contains = false;
        //退货凭证
        if (null != returnGoods.getUserRemarksImg()){
            //判断是否为视频
            String[] suffixs = returnGoods.getUserRemarksImg().split("\\.");
            if (null != suffixs && suffixs.length > 1) {
                String suffix = suffixs[suffixs.length - 1];
                String s = "avi、mov、rmvb、rm、flv、mp4、3gp";
                contains = s.contains(suffix.toLowerCase());
            }
        }
        String remarks = returnGoods.getReturnReason() + "\n" +returnGoods.getUserRemarks();

        ProgressResponse one = new ProgressResponse(1, "提交审核", returnGoods.getCreateTime(),remarks, returnGoods.getUserRemarksImg(), returnGoods.getIsGet(),contains);
        ProgressResponse two = new ProgressResponse(2, "等待审核", returnGoods.getCreateTime(), "您的售后单已申请成功，待售后审核中");
        ProgressResponse three = new ProgressResponse(3, "待处理退货", returnGoods.getServiceApplyTime(), "您的售后申请已通过，请在7天内处理退货申请，否则售后将会关闭");
        ProgressResponse four = new ProgressResponse(4, "待商品入库审核", returnGoods.getReturnExpressTime(), "您的退货信息已提交成功，待入库审核");
        Date waitRefundTime = returnRegister.getCreateTime();
        if (waitRefundTime==null){
            waitRefundTime = (2 == returnGoods.getAfterType() ? returnGoods.getBankerApplyTime() : returnGoods.getServiceApplyTime());
        }
        ProgressResponse five = new ProgressResponse(5, "待财务退款", waitRefundTime, "");
        ProgressResponse eight = new ProgressResponse(8, "售后完成", returnRegister.getRefundTime(), "退款金额已按原路退回（抵扣的余额，积分也将会退至您的账户），请注意查收");


        List<ProgressResponse> progress = new ArrayList<>();
        if (afterType == 1){
            if ((bankerStatus == 1 && serviceStatus == 1 && status == 1) ||
                    (bankerStatus == 2 && serviceStatus == 1 && status == 1) ||
                    (bankerStatus == 3 && serviceStatus == 1 && status == 1)){
                progress.add(new ProgressResponse(1, "提交审核", returnGoods.getCreateTime(),returnGoods.getReturnReason(), returnGoods.getUserRemarksImg(), returnGoods.getIsGet(),contains));
                progress.add(two);
            }else if ((bankerStatus == 1 && serviceStatus == 1 && status == 6) ||
                    (bankerStatus == 3 && serviceStatus == 1 && status == 6) ||
                    (bankerStatus == 3 && serviceStatus == 2 && status == 6) ||
                    (bankerStatus == 2 && serviceStatus == 2 && status == 6) ||
                    (bankerStatus == 2 && serviceStatus == 1 && status == 6)){
                progress.add(new ProgressResponse(1, "提交审核", returnGoods.getCreateTime(),returnGoods.getReturnReason(), returnGoods.getUserRemarksImg(), returnGoods.getIsGet(),contains));
                progress.add(two);
                progress.add(new ProgressResponse(9, "售后关闭", returnGoods.getUpdateTime(), "您的退款申请已撤销，如有需要可在我的售后单里重新提交售后申请"));
            }else if ((bankerStatus == 2 && serviceStatus == 1 && status == 4) ||
                    (bankerStatus == 2 && serviceStatus == 2 && status == 4) ||
                    (bankerStatus == 3 && serviceStatus == 2 && status == 4)){
                progress.add(new ProgressResponse(1, "提交审核", returnGoods.getCreateTime(),returnGoods.getReturnReason(), returnGoods.getUserRemarksImg(), returnGoods.getIsGet(),contains));
                progress.add(two);
                progress.add(new ProgressResponse(5, "待财务退款", null == returnGoods.getServiceApplyTime() ? returnGoods.getBankerApplyTime() : returnGoods.getServiceApplyTime(), "您的售后申请已通过，待财务退款中"));
            }else if ((bankerStatus == 2 && serviceStatus == 1 && status == 9) ||
                    (bankerStatus == 2 && serviceStatus == 2 && status == 9) ||
                    (bankerStatus == 3 && serviceStatus == 2 && status == 9)){
                progress.add(new ProgressResponse(1, "提交审核", returnGoods.getCreateTime(),returnGoods.getReturnReason(), returnGoods.getUserRemarksImg(), returnGoods.getIsGet(),contains));
                progress.add(two);
                progress.add(new ProgressResponse(5, "待财务退款", null == returnGoods.getServiceApplyTime() ? returnGoods.getBankerApplyTime() : returnGoods.getServiceApplyTime(), "您的售后申请已通过，待财务退款中"));
                progress.add(eight);
            }else if ((bankerStatus == 3 && serviceStatus == 3 && status == 5) ||
                    (bankerStatus == 2 && serviceStatus == 3 && status == 5)){
                progress.add(new ProgressResponse(1, "提交审核", returnGoods.getCreateTime(),returnGoods.getReturnReason(), returnGoods.getUserRemarksImg(), returnGoods.getIsGet(),contains));
                progress.add(two);
                progress.add(new ProgressResponse(9, "售后关闭", returnGoods.getServiceApplyTime(), "您的售后申请被驳回，审核意见："+ returnGoods.getServiceRemarks()));
            }
        }else if (afterType == 2){
            if(serviceStatus == 1 && bankerStatus == 1 && status == 1) {
                progress.add(one);
                progress.add(two);
            }else if (serviceStatus == 1 && bankerStatus == 1 && status == 6){
                progress.add(one);
                progress.add(two);
                progress.add(new ProgressResponse(9, "售后关闭", returnGoods.getUpdateTime(), "您的退货退款申请已撤销，如有需要可在我的售后单里重新提交售后申请"));
            }else if (serviceStatus == 2 && bankerStatus == 1 && status == 6){
                progress.add(one);
                progress.add(two);
                progress.add(three);
                progress.add(new ProgressResponse(9, "售后关闭", returnGoods.getUpdateTime(), "您的退货退款申请已撤销，如有需要可在我的售后单里重新提交售后申请"));
            }else if (serviceStatus == 2 && bankerStatus == 1 && status == 2){
                progress.add(one);
                progress.add(two);
                progress.add(new ProgressResponse(3, "待处理退货", returnGoods.getServiceApplyTime(), "您的售后申请已通过，请在7天内处理退货申请，否则售后将会关闭",getDate(returnGoods.getServiceApplyTime(),7*24)));
            }else if (serviceStatus == 3 && bankerStatus == 1 && status == 5){
                progress.add(one);
                progress.add(two);
                progress.add(new ProgressResponse(9, "售后关闭", returnGoods.getServiceApplyTime(), "审核意见:"+returnGoods.getServiceRemarks()));
            }else if (serviceStatus == 2 && bankerStatus == 1 && status == 7){
                progress.add(one);
                progress.add(two);
                progress.add(three);
                progress.add(new ProgressResponse(9, "售后关闭", getDate(returnGoods.getServiceApplyTime(), 24 * 7), "未及时处理退货，售后已关闭"));
            }else if ((serviceStatus == 2 && bankerStatus == 1 && status == 8) || (serviceStatus == 2 && bankerStatus == 1 && status == 3)){
                progress.add(one);
                progress.add(two);
                progress.add(three);
                progress.add(four);
            }else if (serviceStatus == 2 && bankerStatus == 2 && status == 4){
                progress.add(one);
                progress.add(two);
                progress.add(three);
                progress.add(four);
                progress.add(five);
            }else if (serviceStatus == 2 && bankerStatus == 3 && status == 5){
                progress.add(one);
                progress.add(two);
                progress.add(three);
                progress.add(four);
                progress.add(new ProgressResponse(9, "售后关闭", returnGoods.getBankerApplyTime(), "您的退货入库失败, 审核意见:"+returnGoods.getBankerRemarks()));
            }else if (serviceStatus == 2 && bankerStatus == 2 && status == 9){
                progress.add(one);
                progress.add(two);
                progress.add(three);
                progress.add(four);
                progress.add(five);
                progress.add(eight);
            }else if (serviceStatus==2 && status == 9){
                progress.add(one);
                progress.add(two);
                progress.add(three);
                progress.add(four);
                progress.add(five);
                progress.add(eight);
            }else if (serviceStatus==2 && status == 4){
                progress.add(one);
                progress.add(two);
                progress.add(three);
                progress.add(four);
                progress.add(five);
            }
        }else if (afterType == 3){
            if(bankerStatus == 1 && serviceStatus == 1 && status == 1) {
                progress.add(one);
                progress.add(two);
            }else if ((bankerStatus == 1 && serviceStatus == 1 && status == 6) || (bankerStatus == 1 && serviceStatus == 2 && status == 6)){
                progress.add(one);
                progress.add(two);
                progress.add(new ProgressResponse(9, "售后关闭", returnGoods.getUpdateTime(),"您的仅退款申请已撤销，如有需要可在我的售后单里重新提交售后申请"));
            }else if (bankerStatus == 1 && serviceStatus == 2 && status == 4){
                progress.add(one);
                progress.add(two);
                progress.add(five);
            }else if (bankerStatus == 1 && serviceStatus == 2 && status == 9){
                progress.add(one);
                progress.add(two);
                progress.add(five);
                progress.add(eight);
            }else if (bankerStatus == 1 && serviceStatus == 3 && status == 5){
                progress.add(one);
                progress.add(two);
                progress.add(new ProgressResponse(9, "售后关闭", returnGoods.getServiceApplyTime(), "审核意见:"+returnGoods.getServiceRemarks()));
            }
        }
        progress = progress.stream().sorted(Comparator.comparing(ProgressResponse::getId).reversed()).collect(Collectors.toList());
        return CommonResult.success(progress);
    }

    @Override
    public CommonResult getExpressCompany() {
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/order/getExpressList", new HashMap(), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        return commonResult;
    }

    @Override
    public void addExpress(ReturnAddExpressRequest request) {

        ReturnGoods returnGoods = returnGoodsDao.findByServiceNo(request.getServiceNo());
        if(returnGoods == null) {
            throw new ApiException("找不到当前退货单！");
        }
        log.info("============用户提交快递单号===========request.getServiceNo():{},request.getUserId():{}",request.getServiceNo(),request.getUserId());
//        if(request.getUserId() == null || ! request.getUserId().equals(returnGoods.getUserId())) {
//            throw new ApiException("操作权限错误，请联系客服！");
//        }
        if(returnGoods.getStatus() != 2 && returnGoods.getStatus() != 8) {
            throw new ApiException("等待客服审核");
        }
        String returnExpressNo = request.getReturnExpressNo();
        if (MallStringUtil.isSpecialChar(returnExpressNo)) {
            throw new ApiException("寄回单号输入有误,请重新输入!");
        }
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(returnGoods.getOrdersInfoId());
        if (request.getReturnExpressNo().toLowerCase().equals(ordersInfo.getExpressNo().toLowerCase())) {
            throw new ApiException("寄回单号不能和发货单号一致！");
        }

        //寄件人或收件人号码给默认值
        if (StringUtils.isEmpty(request.getRelatedPhone())) {
            Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
            request.setRelatedPhone(orders.getUserPhone());
        }


        returnGoods.setReturnExpressCompany(request.getReturnExpressCompany());
        returnGoods.setReturnExpressNo(request.getReturnExpressNo());
        returnGoods.setReturnOrderNo(request.getReturnOrderNo());
        returnGoods.setUsersPayImg(request.getUsersPayImg());
        returnGoods.setStatus(8);
        returnGoods.setUpdateTime(null);
        returnGoods.setServiceBeizhu(request.getServiceBeizhu());
        returnGoods.setReturnExpressTime(new Date());
        returnGoods.setServiceStatus(2);
        returnGoods.setServiceApplyTime(new Date());
        returnGoods.setRelatedPhone(request.getRelatedPhone());
        returnGoodsMapper.updateByPrimaryKeySelective(returnGoods);

        YxReturnGoods yxReturnGoodsRequest = new YxReturnGoods();
        BeanUtils.copyProperties(returnGoods,yxReturnGoodsRequest);
        updateReturnGoods(yxReturnGoodsRequest);
    }

    @Override
    public ReturnGoodsResponse getReturnStatus(String serviceNo, Integer id) {
        ReturnGoods returnGoods = returnGoodsDao.findByServiceNo(serviceNo);
        if(returnGoods == null) throw new ApiException("找不到当前退货单！");
//        if(id == null || ! id.equals(returnGoods.getUserId())) {
//            throw new ApiException("操作权限错误，请联系客服！");
//        }
        return getReturnGoods(returnGoods);
    }

    @Override
    public List<ReturnGoodsResponse> getReturnList(Integer id) {
        if(id == null) {
            return null;
        }
        return returnGoodsDao.findByUserId(id);
    }

    @Override
    public void revoke(String serviceNo, String token) {
        Users users = usersMapper.queryUsersByToken(token);
        ReturnGoods returnGoods = returnGoodsDao.findByServiceNo(serviceNo);
        if(returnGoods == null) {
            throw new ApiException("找不到当前退货单！");
        }
        if(users == null || ! users.getId().equals(returnGoods.getUserId())) {
            throw new ApiException("操作权限错误，请联系客服！");
        }
        if (returnGoods.getAfterType() == 1 && returnGoods.getStatus() == 4){
            throw new ApiException("该售后已同意退款,不能撤销售后,有疑问请联系客服");
        }
//        String revokeNum = redisService.get("return:good:revoke:" + serviceNo);
//        if (!StringUtils.isEmpty(revokeNum) && Integer.valueOf(revokeNum) == 3) {
//            throw new ApiException("该订单已退货撤回3次,不能发起撤销,有疑问请联系客服,谢谢");
//        }
        //redis保存撤回次数
        redisService.increment("return:good:revoke:" + serviceNo, 1);
        redisService.expire("return:good:revoke:" + serviceNo, 3600 * 24 * 7);
        returnGoods.setStatus(6);
        returnGoods.setUpdateTime(new Date());
        returnGoodsMapper.updateByPrimaryKeySelective(returnGoods);
        //恢复原有的状态
        String orderInfoStatus = adminClient.getRedisString("return:good:orderInfoStatus" + returnGoods.getOrdersInfoId()).getData();
        if (!org.springframework.util.StringUtils.isEmpty(orderInfoStatus)) {
            OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(returnGoods.getOrdersInfoId());
            try {
                //修改供应链售后和订单的状态
                YxReturnGoods yxReturnGoodsRequest = new YxReturnGoods();
                yxReturnGoodsRequest.setServiceNo(returnGoods.getServiceNo());
                yxReturnGoodsRequest.setStatus(6);
                updateReturnGoods(yxReturnGoodsRequest);
            } catch (Exception e) {
                log.error("撤销出错！{}",e);
            }
            try {
                UpdateOrderStatusRequest updateOrderStatusRequest = new UpdateOrderStatusRequest();
                updateOrderStatusRequest.setChildOrderNo(ordersInfo.getChildOrderNo());
                updateOrderStatusRequest.setShopId(supplyApiConfig.getShopId());
                updateOrderStatusRequest.setOrderStatus(Integer.valueOf(orderInfoStatus));
                String json = JSON.toJSONString(updateOrderStatusRequest);
                String s = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/updateOrderStatus", json, supplyApiConfig.getHeadsMap());
                log.info("=====修改订单状态======{}",s);
            } catch (Exception e) {
                e.printStackTrace();
            }
            ordersInfo.setOrderinfoStatus(orderInfoStatus);
            ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
            //查询该子订单所属的主订单有多少个子订单
            OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
            ordersInfoExample.createCriteria().andOrderIdEqualTo(ordersInfo.getOrderId());
            List<OrdersInfo> ordersInfos = ordersInfoMapper.selectByExample(ordersInfoExample);
            if (ordersInfos.size() > 0 && ordersInfos.size() < 2) {
                Orders orders = new Orders();
                orders.setOrderStatus(orderInfoStatus);
                orders.setId(ordersInfo.getOrderId());
                ordersMapper.updateByPrimaryKeySelective(orders);
            }//TODO 如果有多个子订单的情况下,主订单有没有修改,要不要把主订单恢复
        }

    }

    @Override
    public QueryTrackResp getExpress(String serviceNo) {
        ReturnGoods returnGoods = returnGoodsDao.findByServiceNo(serviceNo);
        if(returnGoods == null) {
            throw new ApiException("找不到当前退货单！");
        }
        //根据地址id查一下退货地址信息
        Map map = new HashMap<>();
        map.put("bankerId", String.valueOf(returnGoods.getBankerId()));
        map.put("addressId", String.valueOf(returnGoods.getAddressId()));
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/getReturnGoodAddress", map, supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        List<BankerStoreAddressResponse> result = JSONArray.parseArray(commonResult.getData().toString(), BankerStoreAddressResponse.class);

        if (!CollectionUtils.isEmpty(result) && StringUtils.isEmpty(returnGoods.getReceivingAddress())) {
            if (null != returnGoods.getAddressId()) {
                BankerStoreAddressResponse bankerStoreAddressResponse = result.get(0);
                String pcaAddress = bankerStoreAddressResponse.getProvince()
                                + bankerStoreAddressResponse.getCity()
                                + (null == bankerStoreAddressResponse.getArea() ? "" : bankerStoreAddressResponse.getArea())
                                + bankerStoreAddressResponse.getAddress();
                returnGoods.setReceivingPerson(bankerStoreAddressResponse.getName());
                returnGoods.setReceivingPhone(bankerStoreAddressResponse.getTel());
                returnGoods.setReceivingAddress(pcaAddress);
//                returnGoodsMapper.updateByPrimaryKeySelective(returnGoods);
                returnGoodsMapper.updateReturnGoodsReceiveInfo(returnGoods);
            }
        }
//        QueryTrack queryTrack = new QueryTrack();
//        QueryTrackReq queryTrackReq = new QueryTrackReq();
//        QueryTrackParam queryTrackParam = new QueryTrackParam();
//        queryTrackParam.setCom(returnGoods.getReturnExpressCompany());
//        queryTrackParam.setNum(returnGoods.getReturnExpressNo());
//        queryTrackParam.setPhone(returnGoods.getReceivingPhone());
//        queryTrackReq.setParam(queryTrackParam);
//        queryTrackReq.setCustomer(PropertiesReader.get("customer"));
//        queryTrackReq.setSign(SignUtils.sign(new Gson().toJson(queryTrackParam) + PropertiesReader.get("key") + PropertiesReader.get("customer")));
//        QueryTrackResp resp = queryTrack.queryTrack(queryTrackReq);
//        if(resp != null && resp.getState() != null && resp.getState().equals("3") && returnGoods.getStatus() != 4 && returnGoods.getStatus() != 9&& returnGoods.getStatus() != 5) {
//            returnGoods.setStatus(3);
//            returnGoods.setGetExpressTime(new Date());g
//            returnGoods.setUpdateTime(null);
//            returnGoodsMapper.updateByPrimaryKeySelective(returnGoods);
//        }
        Map<String,String> mapRequest = new HashMap<>();
        mapRequest.put("tel",returnGoods.getReceivingPhone());
        mapRequest.put("expressCompany",returnGoods.getReturnExpressCompany());
        mapRequest.put("expressNo",returnGoods.getReturnExpressNo());
        String s = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/getLogistics", mapRequest, supplyApiConfig.getHeadsMap());
        CommonResult commonResult1 = JSONObject.parseObject(s, CommonResult.class);
        if (null == commonResult1 || 200 != commonResult1.getCode()) {
            return null;
        }
        if (ObjectUtils.isEmpty(commonResult1.getData())){
            return null;
        }
        String s1 = commonResult1.getData().toString();
        if (s1.equals("暂无物流信息！")){
            return null;
        }
        log.info("===commonResult==={}", commonResult);
        List<QueryTrackData> data = JSONArray.parseArray(commonResult1.getData().toString(), QueryTrackData.class);
        QueryTrackResp queryTrackResp = new QueryTrackResp();
        queryTrackResp.setData(data);
        queryTrackResp.setStatus("200");
        return queryTrackResp;
    }

    /**
     * 更新供应链售后信息
     */
    public void updateReturnGoods(YxReturnGoods request){
        request.setShopId(supplyApiConfig.getShopId());
        String json = JSON.toJSONString(request);
        log.info("==============更新供应链售后信息==============参数={}",json);
        HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/updateReturnGoods", json, supplyApiConfig.getHeadsMap());
    }

    /**
     * 查询订单信息
     * 主要查询物流信息（物流公司编码、快递单号、发货时间、是否导出、导出时间）
     */
    public List<OrderQueryResponse> querySupplyChainOrderInfo(List<String> childOrderNo) {
        OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
        orderQueryRequest.setChildOrderNo(childOrderNo);
        String json = com.gexin.fastjson.JSON.toJSONString(orderQueryRequest);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/query", json, supplyApiConfig.getHeadsMap());
        if (org.springframework.util.StringUtils.isEmpty(resultJson)) {
            return new ArrayList<>();
        }
        JSONObject parse = JSON.parseObject(resultJson);
        List<OrderQueryResponse> orderQueryResponses = JSONObject.parseArray(parse.getString("data"), OrderQueryResponse.class);
        return orderQueryResponses;
    }

    @Override
    public CommonResult addAppCommitRedis() {
        Set<String> listKey = redisService.getListKey("return:good:orderInfoStatus");
        for (String key : listKey) {
            String value = redisService.get(key);
            adminClient.updateRedisString(key,value,3600 * 24 * 180);
        }
        return CommonResult.success();
    }

    @Override
    public  List<Map<String, String>> queryExpressCompany(String num) {
        List<Map<String, String>> list = new ArrayList<>();
        AutoNum autoNum = new AutoNum();
        String key = PropertiesReader.get("key");
        List<AutoNumResp> comByNumList = autoNum.getComByNumList(key, num);
        if (!CollectionUtils.isEmpty(comByNumList)) {
            for (AutoNumResp autoNumResp : comByNumList) {
                Map<String, String> returnMap = new HashMap<>();
                returnMap.put("expressKey",autoNumResp.getName());
                returnMap.put("expressValue",autoNumResp.getComCode());
                list.add(returnMap);
            }
        }
        return list;
    }
}
